package com.project2.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project2.bean.PageBo;
import com.project2.bean.ResultVo;
import com.project2.bean.po.*;
import com.project2.bean.vo.*;
import com.project2.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.util.ArrayUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：HsDsg
 * @date ：2022/8/14 20:42
 * @description：TODO
 */

@Service
public class WxGoodsServiceImpl implements WxGoodsService {

    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketCategoryMapper categoryMapper;

    @Autowired
    MarketGoodsAttributeMapper attributeMapper;

    @Autowired
    MarketBrandMapper brandMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;

    @Autowired
    MarketIssueMapper issueMapper;

    @Autowired
    MarketGoodsProductMapper productMapper;

    @Autowired
    MarketGoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    MarketCollectMapper collectMapper;

    @Autowired
    MarketFootprintMapper marketFootprintMapper;

    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;

    @Override
    public long goodsCount() {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        long count = goodsMapper.countByExample(marketGoodsExample);
        return count;
    }

    @Override
    public ResultVo getRestsCategoryByCategoryId(Integer id) {
        int pid = categoryMapper.selectPidByCategoryId(id);
        if (pid == 0) {
            List<MarketCategory> marketCategories = categoryMapper.selectAllCategory(id);
            MarketCategory marketCategory = marketCategories.get(0);
            MarketCategory marketCategory1 = categoryMapper.selectByPrimaryKey(id);

            WxCategoryVo wxCategoryVo = new WxCategoryVo();
            wxCategoryVo.setBrotherCategory(marketCategories);
            wxCategoryVo.setCurrentCategory(marketCategory);
            wxCategoryVo.setParentCategory(marketCategory1);

            return ResultVo.ok(wxCategoryVo);
        } else {
            MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
            MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
            criteria.andPidEqualTo(pid)
                    .andDeletedEqualTo(false);
            List<MarketCategory> brotherCategory = categoryMapper.selectByExample(marketCategoryExample);

            MarketCategory currentCategory = categoryMapper.selectByPrimaryKey(id);
            MarketCategory parentCategory = categoryMapper.selectByPrimaryKey(currentCategory.getPid());
            WxCategoryVo wxCategoryVo = new WxCategoryVo();
            wxCategoryVo.setBrotherCategory(brotherCategory);
            wxCategoryVo.setCurrentCategory(currentCategory);
            wxCategoryVo.setParentCategory(parentCategory);
            return ResultVo.ok(wxCategoryVo);
        }


        //根据id找到brother
//        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
//        MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
//        criteria.andPidEqualTo(pid)
//                .andDeletedEqualTo(false);
//        List<MarketCategory> marketCategories = categoryMapper.selectByExample(marketCategoryExample);

        //根据pid找到brother


        //根据id找到currentCategory
//        MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(id);


        //根据pid找到parent
//        MarketCategory marketCategory1 = categoryMapper.selectByPrimaryKey(pid);

//        MarketCategory marketCategory1 = categoryMapper.selectParentCategory(pid);

        //根据id找到parent
    }


    @Override
    public WxGoodsListVo getGoodsByCategoryId(Integer categoryId, Integer page, Integer limit) {
//        根据categoryId获取到被过滤掉的
        int pid = categoryMapper.selectPidByCategoryId(categoryId);

        //通过pid找到所有的categoryId
        List<Integer> integers = categoryMapper.selectCategoryIdByPid(pid);

        ArrayList<MarketCategory> categories = new ArrayList<>();

        int count = 0;
        for (Integer integer : integers) {
            MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(integer);

            if (categories.size() == 0) {
                categories.add(marketCategory);
            } else {
                for (int i = 0; i < categories.size(); i++) {
                    if (!marketCategory.getId().equals(categories.get(i).getId())) {
                        count++;
                    }
                    if (i == categories.size() - 1) {
                        if (count == categories.size()) {
                            categories.add(marketCategory);
                        }
                    }
                }
            }
        }


//        被过滤掉的
//        List<MarketCategory> marketCategories = categoryMapper.selectCategory(pid, categoryId);
//        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
//        MarketCategoryExample.Criteria criteria1 = marketCategoryExample.createCriteria();
//        criteria1.andIdEqualTo(pid)
//                .andDeletedEqualTo(false);
//        List<MarketCategory> marketCategories = categoryMapper.selectByExample(marketCategoryExample);
//

        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();

        criteria.andDeletedEqualTo(false)
                .andCategoryIdEqualTo(categoryId);


        PageHelper.startPage(page, limit);
        PageHelper.startPage(page, limit);

        //该分类下全部商品
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(marketGoodsExample);

        WxGoodsListVo wxGoodsListVo = new WxGoodsListVo();
        wxGoodsListVo.setFilterCategoryList(categories);
        wxGoodsListVo.setList(marketGoods);

        PageInfo pageInfo = new PageInfo(wxGoodsListVo.getList());

        WxGoodsListVo data = WxGoodsListVo.data(pageInfo);
        wxGoodsListVo.setPages(data.getPages());
        wxGoodsListVo.setLimit(data.getLimit());
        wxGoodsListVo.setPage(data.getPage());
        wxGoodsListVo.setTotal(data.getTotal());


        return wxGoodsListVo;
    }


    @Override
    public WxGoodsListVo getGoodsByBrandId(Integer brandId, Integer page, Integer limit) {

//
//        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
//        MarketCategoryExample.Criteria categoryCriteria = marketCategoryExample.createCriteria();


        //        被过滤掉的MarketCategoryList
        ArrayList<MarketCategory> categoryList = new ArrayList<>();

        //查询到所有CategoryId
        List<Integer> integers = goodsMapper.selectCategoryIdByBrandId(brandId);

        int count = 0;
        for (Integer integer : integers) {
            MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(integer);

            if (categoryList.size() == 0) {
                categoryList.add(marketCategory);
            } else {
                for (int i = 0; i < categoryList.size(); i++) {
                    if (!marketCategory.getId().equals(categoryList.get(i).getId())) {
                        count++;
                    }
                    if (i == categoryList.size() - 1) {
                        if (count == categoryList.size()) {
                            categoryList.add(marketCategory);
                        }
                    }
                }
            }
        }


//
//        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
//        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
//        criteria.andDeletedEqualTo(false)
//                .andBrandIdNotEqualTo(brandId);
//        List<MarketGoods> marketGoods = goodsMapper.selectByExample(marketGoodsExample);
//        for (MarketGoods marketGood : marketGoods) {
//            Integer categoryId = marketGood.getCategoryId();
//            categoryCriteria.andIdEqualTo(categoryId)
//                            .andDeletedEqualTo(false);
//            List<MarketCategory> marketCategories = categoryMapper.selectByExample(marketCategoryExample);
//            for (int i = 0; i <marketCategories.size(); i++) {
//                if (i==0){
//                    categoryList.add(marketCategories.get(i));
//                }else if (marketCategories.get(i).getPid()!=marketCategories.get(i-1).getPid()){
//                    categoryList.add(marketCategories.get(i));
//                }
//            }
//        }


        PageHelper.startPage(page, limit);

        List<MarketGoods> marketGoods1 = goodsMapper.selectGoodsbYBrandId(brandId);


        WxGoodsListVo wxGoodsListVo = new WxGoodsListVo();
        wxGoodsListVo.setFilterCategoryList(categoryList);
        wxGoodsListVo.setList(marketGoods1);

        PageInfo pageInfo = new PageInfo(marketGoods1);

        WxGoodsListVo data = WxGoodsListVo.data(pageInfo);
        wxGoodsListVo.setPages(data.getPages());
        wxGoodsListVo.setLimit(data.getLimit());
        wxGoodsListVo.setPage(data.getPage());
        wxGoodsListVo.setTotal(data.getTotal());


        return wxGoodsListVo;


    }


    @Override
    public WxGoodsDetailVo getGoodsDetail(Integer id) {
        WxGoodsDetailVo wxGoodsDetailVo = new WxGoodsDetailVo();
        WxCommentVo wxCommentVo = new WxCommentVo();

        //通过商品id获取商品参数信息
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria criteria = marketGoodsAttributeExample.createCriteria();
        criteria.andGoodsIdEqualTo(id)
                .andDeletedEqualTo(false);
        List<MarketGoodsAttribute> goodsAttributes = attributeMapper.selectAttributeByGoodsId(id);

        //制造商信息
        int brandId = goodsMapper.selectBrandIdByGoodsId(id);
        MarketBrand marketBrand = brandMapper.selectByPrimaryKey(brandId);

        //评论信息
//        int categoryId = goodsMapper.selectCategoryIdByGoodsId(id);
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria criteria1 = marketCommentExample.createCriteria();
//        criteria1.andValueIdEqualTo(categoryId)
        criteria1.andValueIdEqualTo(id)
                .andDeletedEqualTo(false);
        List<MarketComment> marketCommentsByCategoryId = commentMapper.selectByExample(marketCommentExample);
        if (marketCommentsByCategoryId.size() == 0) {
            MarketCommentExample.Criteria criteria2 = marketCommentExample.createCriteria();
            //clear不可用来清除
            criteria2.andValueIdEqualTo(id)
                    .andDeletedEqualTo(false);

//            marketCommentExample.clear();
//            criteria1.andValueIdEqualTo(id)
//                    .andDeletedEqualTo(false);
            List<MarketComment> marketCommentsByGoodsId = commentMapper.selectByExample(marketCommentExample);
            wxCommentVo.setData(marketCommentsByGoodsId);
            wxCommentVo.setCount(marketCommentsByGoodsId.size());
        }
        wxCommentVo.setData(marketCommentsByCategoryId);
        wxCommentVo.setCount(marketCommentsByCategoryId.size());


        MarketGrouponRulesExample grouponRulesExample = new MarketGrouponRulesExample();
        MarketGrouponRulesExample.Criteria criteria5 = grouponRulesExample.createCriteria();
        criteria5.andGoodsIdEqualTo(id)
                .andDeletedEqualTo(false);
        List<MarketGrouponRules> marketGrouponRules = grouponRulesMapper.selectByExample(grouponRulesExample);


        //商品
        MarketGoods goods = goodsMapper.selectByPrimaryKey(id);

        //购买提示
        List<MarketIssue> marketIssues = issueMapper.selectAllIssue();

        //productList
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria criteria2 = marketGoodsProductExample.createCriteria();
        criteria2.andGoodsIdEqualTo(id)
                .andDeletedEqualTo(false);
        List<MarketGoodsProduct> marketGoodsProducts = productMapper.selectByExample(marketGoodsProductExample);




        //找出该商品所有规格数量
        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria criteria3 = specificationExample.createCriteria();
        criteria3.andGoodsIdEqualTo(id)
                .andDeletedEqualTo(false);
        List<MarketGoodsSpecification> marketGoodsSpecifications = goodsSpecificationMapper.selectByExample(specificationExample);

        ArrayList<String> SpecificationsName = new ArrayList<>();

        //返回Specifcation
        ArrayList<SpecifcationVo> specifcationVos = new ArrayList<>();

        if (marketGoodsSpecifications.size() == 0) {
            wxGoodsDetailVo.setSpecificationList(specifcationVos);
        } else if (marketGoodsSpecifications.size() == 1) {
            SpecifcationVo specifcationVo1 = new SpecifcationVo();
            specifcationVo1.setName(marketGoodsSpecifications.get(0).getSpecification());
            specifcationVo1.setValueList(marketGoodsSpecifications);
            specifcationVos.add(specifcationVo1);
            wxGoodsDetailVo.setSpecificationList(specifcationVos);
        }else {
            for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecifications) {
                SpecificationsName.add(marketGoodsSpecification.getSpecification());
            }
            List<String> collect = SpecificationsName.stream().distinct().collect(Collectors.toList());
            for (String s : collect) {
                MarketGoodsSpecificationExample specificationExample1 = new MarketGoodsSpecificationExample();
                MarketGoodsSpecificationExample.Criteria criteria4 = specificationExample1.createCriteria();
                criteria4.andGoodsIdEqualTo(id)
                        .andSpecificationEqualTo(s);
                List<MarketGoodsSpecification> marketGoodsSpecifications1 = goodsSpecificationMapper.selectByExample(specificationExample1);
                SpecifcationVo specifcationVo = new SpecifcationVo();
                specifcationVo.setName(s);
                specifcationVo.setValueList(marketGoodsSpecifications1);
                specifcationVos.add(specifcationVo);
        }
            wxGoodsDetailVo.setSpecificationList(specifcationVos);
        }


        //用户收藏
        MarketCollectExample marketCollectExample = new MarketCollectExample();
        MarketCollectExample.Criteria criteria4 = marketCollectExample.createCriteria();
        criteria4.andValueIdEqualTo(id)
                .andDeletedEqualTo(false);
        List<MarketCollect> marketCollects = collectMapper.selectByExample(marketCollectExample);


        wxGoodsDetailVo.setAttribute(goodsAttributes);
        wxGoodsDetailVo.setBrand(marketBrand);
        wxGoodsDetailVo.setComment(wxCommentVo);
        wxGoodsDetailVo.setGroupon(marketGrouponRules);
        wxGoodsDetailVo.setInfo(goods);
        wxGoodsDetailVo.setIssue(marketIssues);
        wxGoodsDetailVo.setProductList(marketGoodsProducts);
        wxGoodsDetailVo.setShare(true);
        wxGoodsDetailVo.setShareImage(goods.getShareUrl());

        wxGoodsDetailVo.setUserHasCollect(marketCollects.size());

        return wxGoodsDetailVo;
    }

    @Override
    public WxGoodsListVo getRelatedGoods(Integer id) {
//        int brandId = goodsMapper.selectBrandIdByGoodsId(id);
        int categoryId = goodsMapper.selectCategoryIdByGoodsId(id);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId)
                .andDeletedEqualTo(false);

        PageHelper.startPage(1, 6);
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(marketGoodsExample);
        PageInfo pageInfo = new PageInfo(marketGoods);
        WxGoodsListVo wxGoodsListVo = new WxGoodsListVo();
        wxGoodsListVo.setTotal((int) pageInfo.getTotal());
        wxGoodsListVo.setLimit(pageInfo.getPageSize());
        wxGoodsListVo.setPage(pageInfo.getPageNum());
        wxGoodsListVo.setPages(pageInfo.getPages());
//        wxGoodsListVo.data(pageInfo);
        wxGoodsListVo.setList(marketGoods);
        return wxGoodsListVo;
    }

    @Override
    public void addFootprintByGoodsIdAndUserId(Integer id, Integer userId) {
        MarketFootprint marketFootprint = new MarketFootprint();
        marketFootprint.setUserId(userId);
        marketFootprint.setGoodsId(id);
        Date date = new Date();
        marketFootprint.setAddTime(date);
        marketFootprint.setUpdateTime(date);
        marketFootprintMapper.insertSelective(marketFootprint);
    }

    @Override
    public List<MarketFootprint> queryFootprintByGoodsIdAndUserIdAndDeleted(Integer id, Integer userId, Integer deleted) {
        List<MarketFootprint> marketFootprintList = marketFootprintMapper.queryFootprintListByGoodsIdAndUserIdAndDeleted(id,userId,deleted);
        return marketFootprintList;
    }

    @Override
    public void deleteFootprintById(Integer id) {
        marketFootprintMapper.deleteFootprintById(id);
    }
    /**
    *@Author: MH
    *@date: 2022/8/17 13:54
    *@Description:根据关键字搜索商品,并且把这个关键字加入到搜索历史中
    */
    @Override
    public WxGoodsListVo getGoodsByKeyword(String keyword, PageBo pageBo,MarketUser user) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andNameLike("%" + keyword + "%");
        PageHelper.startPage(pageBo.getPage(),pageBo.getLimit());
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(marketGoodsExample);
        List<MarketCategory> marketCategories = new ArrayList<>();
        for (MarketGoods marketGood : marketGoods) {
            MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(marketGood.getCategoryId());
            marketCategories.add(marketCategory);
        }
        WxGoodsListVo wxGoodsListVo = new WxGoodsListVo();
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(marketGoods);
        wxGoodsListVo.setLimit(marketGoodsPageInfo.getSize());
        wxGoodsListVo.setPage(marketGoodsPageInfo.getPageNum());
        wxGoodsListVo.setPages(marketGoodsPageInfo.getPages());
        wxGoodsListVo.setTotal((int)marketGoodsPageInfo.getTotal());
        wxGoodsListVo.setList(marketGoods);
        wxGoodsListVo.setFilterCategoryList(marketCategories);

        // 下面是把keyword加入搜索历史表中
        // 接下来是将搜索的keyword加入搜索历史表
        MarketSearchHistory marketSearchHistory = new MarketSearchHistory();
        MarketSearchHistoryExample marketSearchHistoryExample = new MarketSearchHistoryExample();
        MarketSearchHistoryExample.Criteria criteria1 = marketSearchHistoryExample.createCriteria();
        criteria1.andKeywordEqualTo(keyword)
                .andDeletedEqualTo(false);
        List<MarketSearchHistory> marketSearchHistories = marketSearchHistoryMapper.selectByExample(marketSearchHistoryExample);
        Date date = new Date();
        // 如果之前搜索过这个关键词,就只需要更新时间即可
        if (marketSearchHistories.size() != 0) {
            marketSearchHistory.setUpdateTime(date);
            marketSearchHistoryMapper.updateByExampleSelective(marketSearchHistory, marketSearchHistoryExample);
            return wxGoodsListVo;
        }
        // 走到这说明从未搜索过这个关键词或者这个搜索记录被删了
        MarketSearchHistoryExample marketSearchHistoryExample1 = new MarketSearchHistoryExample();
        MarketSearchHistoryExample.Criteria criteria2 = marketSearchHistoryExample1.createCriteria();
        // 先考虑搜索记录曾经被删除的情况,那么只需要更新时间和更改deleted状态即可
        criteria2.andDeletedEqualTo(true)
                .andKeywordEqualTo(keyword);
        List<MarketSearchHistory> marketSearchHistories1 = marketSearchHistoryMapper.selectByExample(marketSearchHistoryExample1);
        if(marketSearchHistories1.size()!=0) {
            marketSearchHistory.setUpdateTime(date);
            marketSearchHistory.setDeleted(false);
            marketSearchHistoryMapper.updateByExampleSelective(marketSearchHistory, marketSearchHistoryExample1);
            return wxGoodsListVo;
        }
        // 走到这里说明从未搜过这个关键词
        MarketSearchHistoryExample.Criteria criteria3 = marketSearchHistoryExample.createCriteria();
        MarketSearchHistory marketSearchHistory1 = new MarketSearchHistory();
        marketSearchHistory1.setDeleted(false);
        marketSearchHistory1.setUpdateTime(date);
        marketSearchHistory1.setAddTime(date);
        marketSearchHistory1.setKeyword(keyword);
        marketSearchHistory1.setUserId(user.getId());
        marketSearchHistoryMapper.insertSelective(marketSearchHistory1);
        return wxGoodsListVo;
    }

    @Override
    public List<Integer> queryAllGoodsId() {
        // todo: 需要去重
        return marketFootprintMapper.queryAllGoodsId();
    }

}

